//
//  HomeEqualizerCellViewModel.swift
//  EasePods
//
//  Created by 易先生 on 2024/4/9.
//

import UIKit
import RxSwift
import RxCocoa
import CRPEarPhone

public class HomeEqualizerCellViewModel: ViewModel {
    
    /// 输入
    public let selectItme = PublishRelay<CRPEQType>()
    
    // 输出
    public let equalizerItems = BehaviorRelay<[(item: CRPEQType, isSelect: Bool)]>(value: [])
    
    override init() {
        super.init()
        
        var config: CRPEQSetttingModel?
        
        // 默认数据
        let items: [CRPEQType] = [.normal, .rock, .pop, .jazz, .country, .classic]
        equalizerItems.accept(items.map { (item: $0, isSelect: false) })
        
        /// 设置 EQ模式
        let selectAction = selectItme.map { item in
            if let config = config {
                config.currentState = item
                BluetoothManager.shared.sendEQSetting(model: config)
            }
        }
        
        /// 查询 EQ 模式，初始化及设置 EQ 模式后查询
        Observable.of(Observable.just(()), selectAction)
            .merge()
            .flatMapLatest { _ in
                return BluetoothManager.shared.queryEQSetting()
                    .map { settingModel in
                        config = settingModel
                        let items: [CRPEQType] = [.normal, .rock, .pop, .jazz, .country, .classic]
                        return items.map{ (item: $0, isSelect: $0.rawValue == settingModel.currentState.rawValue) }
                    }
            }
            .bind(to: self.equalizerItems).disposed(by: rx.disposeBag)
    }
}
